import {guid} from '@/utils';
import FieldComponentFormulaTypes, {
  FormulaTypes
} from '@comp/hhd/design/FormDesigner/field/comps/form/FieldValueFormulaGroups/configs/FieldComponentFormulaTypes';

export function createFormDefinition() {
  return {
    id: guid(),
    formName: '单据名称',
    formKey: undefined,
    tableName: undefined,
    fields: [],
    subForms: [],
    formMain: true,//主表
    views: [createFormView(true)],
    fieldLastIndex: 0,
    subTableIndex: 0,
    hasFlow: false,

    //下面是一些子表字段
    actions: [],
    menus: [],
    flows: [],
    relations: [],
    fieldValueFormulaGroups: [],
    fieldActionFormulaGroups: [],
    fieldClearFormulas: [],
    formCheckGroups: [],
    subFormAuthFormulas: [],
  };
}

export function createSubFormAuthFormula() {
  return {
    id: guid(),
    formula: undefined,
    formulaTitle: undefined,
    sort: undefined,

    actionId: undefined,
    subFormId: undefined,
    formId: undefined,

    addRow: false,
    copyRow: false,
    removeRow: false,
    clearRow: false,
    moveUp: false,
    moveDown: false,
  };
}

export function createFormCheckGroup() {
  return {
    id: guid(),
    formId: undefined,
    checkGroupName: undefined,
    actionIds: undefined,
    remark: undefined,
    enable: true,
    sort: undefined,
    checkRules: [createCheckRule()]
  };
}

export function createCheckRule() {
  return {
    id: guid(),
    formId: undefined,
    groupId: undefined,
    subFormId: undefined,
    ifFormula: undefined,
    ifFormulaTitle: undefined,
    checkFormula: undefined,
    checkFormulaTitle: undefined,
    message: undefined,
    content: undefined,
    sort: undefined,
    forceCheck: true,
    remark: undefined,
    enable: true,
  };
}

export function createFieldClearFormula() {
  return {
    id: guid(),
    fieldId: undefined,
    formula: undefined,
    formulaTitle: undefined,
    sort: undefined,
    clearFieldIds: undefined
  };
}

export function createField() {
  return {
    id: guid(),
    label: undefined,
    fieldName: undefined,
    fieldTitleName: undefined,
    component: 'input',
    length: 255,
    format: undefined,
    maxValue: undefined,
    minValue: undefined,
    placeholder: undefined,
    dict: undefined,
    dictType: undefined, //数据字典的类型(系统字典system, 应用字典app, 基本档案baseData)
    customComponent: false, //是否是自定义组件
    viewComponent: false, //是否是视图中用的组件
    exts: {}, //给自定义组件用的扩展配置项
  };
}

export function createFormulaGroup() {
  return {
    id: guid(),
    fieldId: undefined,
    groupKey: undefined,
    ifFormula: undefined,
    elseFormula: undefined,
    thenFormula: undefined,
    sort: undefined,
    forAction: undefined,
    ifFormulaTitle: undefined,
    thenFormulaTitle: undefined,
    elseFormulaTitle: undefined,
    auth: undefined,
    required: false,
    actionId: undefined
  };
}

export function createSubTable(formDefinition) {
  let index = ++formDefinition.subTableIndex;
  let res = {
    id: guid(),
    formName: '明细表' + index,
    tableName: undefined, //表名
    formKey: 'subTable_' + index,
    formMain: false,//明细表
    fields: [],
  };
  formDefinition.subForms.push(res);
  return res;
}

export function createFormView(mainView = false) {
  return {
    id: guid(),
    html: '',
    templateConfigs: [],
    pageWidth: 960,
    viewName: mainView ? '主视图' : '新建视图',
    mainView,
    components: [],
  };
}

export function createDefaultAction(formDefinition, actionName, actionType, preset) {
  let res = {actionName, actionType, preset, id: guid()};
  let {fields, subForms} = formDefinition, fieldActions = [];
  for (let i = 0; i < fields.length; i++) {
    fieldActions.push(createFieldAction(actionType, fields[i], formDefinition.id));
  }

  (subForms || []).forEach(s => {
    let fields = s.fields || [];
    for (let i = 0; i < fields.length; i++) {
      fieldActions.push(createFieldAction(actionType, fields[i], s.id));
    }
  });

  res.fieldActions = fieldActions;
  res.subFormActions = createSubFormAction(formDefinition, actionType);
  return res;
}

export function createFieldAction(actionType, field, formId) {
  let auth = actionType === 'add' ? 'edit' : 'browse';
  return {
    auth,
    formId,
    fieldId: field.id,
    required: false,
    id: guid(),
    defaultValueType: 'manual', // manual 手动设置, system 系统变量
    defaultValue: undefined,
    defaultTitle: undefined
  };
}

export function createFormMenu() {
  return {
    id: guid(),
    showFields: undefined,
    orderFields: undefined,
    searchFields: undefined,
    searchQuerys: undefined,
    menuName: undefined,
    remark: undefined,
    buttons: undefined,
    viewId: undefined, //编辑视图id
    actionId: undefined, //编辑权限id
    detailViews: []
  };
}

export function createFormMenuDetailView() {
  return {
    formId: undefined,
    viewId: undefined,
    formMenuId: undefined,
    actionId: undefined,
    sort: undefined
  };
}

export function createFormMenuButton() {
  return {
    id: guid(),
    formId: undefined,
    formMenuId: undefined,
    buttonName: undefined,
    buttonComponent: undefined,
    icon: undefined,
    config: undefined,
    rowButton: false,
    buttonType: false,
    batchButton: false,
    showName: false,
    buttonShape: 'round',
  };
}

export function createSubFormAction(formDefinition, actionType) {
  return (formDefinition && formDefinition.subForms || []).map(subForm => ({
    id: guid(),
    subFormId: subForm.id,
    addRow: 'add' === actionType,
    removeRow: 'add' === actionType,
    copyRow: 'add' === actionType,
    clearRow: 'add' === actionType,
    moveUp: 'add' === actionType,
    moveDown: 'add' === actionType,
  }));
}

export function createMenuSearchQuery() {
  return {
    id: guid(),
    formId: undefined,
    fieldId: undefined,
    fieldValue: undefined,
    fieldTitle: undefined,
    fieldValueType: undefined,
    searchCondition: undefined,
    formMenuId: undefined,
    prefix: undefined,
    suffix: undefined,
    joinType: 'and'
  };
}

export function createFormDefinitionVO(formDefinition) {
  let data = JSON.parse(JSON.stringify(formDefinition));
  resolveFieldsVO(data.fields || []);
  resolveViewsVO(data.views || []);
  resolveSubFormVo(data.subForms || []);
  resolveFormMenuVo(data.menus || []);
  return data;
}

function resolveFormMenuVo(menus) {
  menus.forEach(menu => {
    (menu.buttons || []).forEach(button => {
      button.config = button.config && JSON.stringify(button.config) || '{}';
    });
  });
}

function resolveSubFormVo(subForms) {
  subForms.forEach(subForm => {
    let fields = subForm.fields || [];
    fields.forEach(field => {
      field.exts = JSON.stringify(field.exts);
    });
  });
}

function resolveViewsVO(views) {
  views.forEach(view => {
    view.components = view.components && JSON.stringify(view.components) || undefined;
    view.templateConfigs = view.templateConfigs && JSON.stringify(view.templateConfigs) || undefined;
  });
}

function resolveFieldsVO(fields) {
  fields.forEach(field => {
    field.exts = field.exts && JSON.stringify(field.exts) || undefined;
  });
}

export function readFormDefinitionVo(formDefinitionVo) {
  formDefinitionVo = formDefinitionVo || {};
  formDefinitionVo = JSON.parse(JSON.stringify(formDefinitionVo));
  readFieldsVO(formDefinitionVo.fields || []);
  readViewsVO(formDefinitionVo.views || []);
  readSubFormVo(formDefinitionVo.subForms || []);
  readMenus(formDefinitionVo.menus || []);
  return formDefinitionVo;
}

function readMenus(menus) {
  menus.forEach(menu => {
    let buttons = menu.buttons || [];
    buttons.forEach(button => {
      button.config = JSON.parse(button.config) || {};
    });
  });
}

function readSubFormVo(subForms) {
  subForms.forEach(subForm => {
    readFieldsVO(subForm.fields || []);
  });
}

function readViewsVO(views) {
  views.forEach(view => {
    view.components = view.components && JSON.parse(view.components) || [];
    view.templateConfigs = view.templateConfigs && JSON.parse(view.templateConfigs) || undefined;
  });
}

function readFieldsVO(fields) {
  fields.forEach(f => {
    f.exts = f.exts && JSON.parse(f.exts) || [];
  });
}

export function createFlow() {
  return {
    id: guid(),
    formType: undefined,
    titleFormula: undefined,
    titleFormulaText: undefined,
    beforeListeners: undefined,
    afterListeners: undefined,
    model: undefined,
    version: 0,
    enable: true,
    flowModelName: '新建流程',
  };
}

export function getFormDefinitionVariables(formDefinition) {
  let {fields, subForms} = formDefinition, res = [];
  fields.forEach(item => {
    res.push({
      formId: formDefinition.id,
      fieldId: item.id,
      variableName: item.id,
      variableType: FieldComponentFormulaTypes[item.component] || FormulaTypes.string,
      title: `[主表] ${item.label}`,
      variableTitle: `${item.label}`
    });
  });
  (subForms || []).forEach((subForm) => {
    (subForm.fields || []).forEach(item => {
      res.push({
        fieldId: item.id,
        formId: item.formId,
        variableName: `${subForm.id}.${item.id}`,
        variableType: FieldComponentFormulaTypes[item.component] || FormulaTypes.string,
        title: `[${subForm.formName}] ${item.label}`,
        variableTitle: `${item.label}`
      });
    });
  });
  return res;
}

export function getFormFieldById(formDefinition, fieldId) {
  let {fields, subForms} = formDefinition, res = [];
  for (let i = 0; i < fields.length; i++) {
    if (fields[i].id === fieldId) return fields[i];
  }
  subForms = subForms || [];
  for (let i = 0; i < subForms.length; i++) {
    fields = subForms[i].fields || [];
    for (let j = 0; j < fields.length; j++) {
      if (fields[j].id === fieldId) return fields[j];
    }
  }
}

export function getFormByFieldId(formDefinition, fieldId) {
  let {fields, subForms} = formDefinition, res = [];
  if (fields.findIndex(f => f.id === fieldId) !== -1) return formDefinition
  subForms = subForms || [];
  for (let i = 0; i < subForms.length; i++) {
    fields = subForms[i].fields || [];
    for (let j = 0; j < fields.length; j++) {
      if (fields[j].id === fieldId) return subForms[i];
    }
  }
}

export function getTableNameByFieldId(fieldId, formDefinition) {
  let {fields, subForms} = formDefinition;
  fields = fields || [];
  subForms = subForms || [];
  for (let i = 0; i < fields.length; i++) {
    if (fields[i].id === fieldId) return formDefinition.tableName;
  }
  for (let i = 0; i < subForms.length; i++) {
    fields = subForms[i].fields || [];
    for (let j = 0; j < fields.length; j++) {
      if (fields[j].id === fieldId) return subForms[i].tableName;
    }
  }
  return undefined;
}

export function copyFormModel(formModel, formDefinition) {
  let res = JSON.parse(JSON.stringify(formModel));
  let subForms = formDefinition.subForms || [];
  res.id = undefined;

  subForms.forEach(subForm => {
    let list = res[subForm.id] || [];
    list.forEach(item => {
      item.id = undefined;
      item.formId = undefined;
      item.form_id = undefined;
    });
  });

  return res;
}

export function fieldCanMapping(sourceField, targetField) {
  if(sourceField.component === 'input' && targetField.component === 'text' ||
    sourceField.component === 'text' && targetField.component === 'input') return true

  if(sourceField.component === 'input' && targetField.component === 'rowIndex' ||
    sourceField.component === 'rowIndex' && targetField.component === 'input') return true

  if(sourceField.component === 'text' && targetField.component === 'rowIndex' ||
    sourceField.component === 'rowIndex' && targetField.component === 'text') return true

  if(sourceField.component === 'text' && targetField.component === 'formCode' ||
    sourceField.component === 'formCode' && targetField.component === 'text') return true

  if(sourceField.component === 'input' && targetField.component === 'formCode' ||
    sourceField.component === 'formCode' && targetField.component === 'input') return true

  if(sourceField.component !== targetField.component || sourceField.dict !== targetField.dict ) {
    return false;
  }


  return true;
}

export function getAllFields(formDefinition, includeForms = undefined) {
  formDefinition = formDefinition || [];
  let res = [], fields = formDefinition.fields || [], subForms = formDefinition.subForms || [], subFormMap = {};
  includeForms = includeForms || undefined;
  if (!includeForms || includeForms.includes(formDefinition.id)) {
    res.push(...fields);
  }
  subForms.forEach(subForm => {
    if (includeForms && !includeForms.includes(subForm.id)) return;
    subFormMap[subForm.id] = subForm;
    fields = subForm.fields || [];
    res.push(...fields);
  });

  function getFormNameById(formId) {
    if (formId === formDefinition.id) return '[主表]';
    return `[${subFormMap[formId].formName}]`;
  }

  return res.map(f => ({...f, title: `${getFormNameById(f.formId)} ${f.label}`}));
}